# coding=utf-8
import os
import re
from tkinter import *
from tkinter import filedialog
from tkinter import font
from tkinter import messagebox
from tkinter.ttk import Combobox
from MergeRegistrationForm.core import read_word, read_excel
from utils.file import get_sort_file_list


class MyGUI:
    def __init__(self, window):
        """
        初始化窗口
        :param window:
        """
        self.window = window

    def set_window_style(self):
        """
        设置窗口样式
        :return:
        """
        screen_width = self.window.winfo_screenwidth()
        screen_height = self.window.winfo_screenheight()
        width, height = 400, 260
        x = int(screen_width / 2 - width / 2)
        y = int(screen_height / 2 - height / 2)
        size = '{}x{}+{}+{}'.format(width, height, x, y)  # 设置宽高和居中显示
        self.window.geometry(size)
        self.window.title("合并报名表-王凤龙")

    def set_window_menu(self):
        """
        设置菜单
        :return:
        """
        menubar = Menu(self.window)
        menubar.add_command(label="联系我", command=lambda: messagebox.showinfo("联系我", "微信号：i-aisx"))
        menubar.add_command(label="重置", command=lambda: self.reset())
        menubar.add_command(label="关闭", command=lambda: self.window.destroy())
        self.window.config(menu=menubar)

    def set_window_layout(self):
        """
        设置窗口布局
        :return:
        """
        """选择目录"""
        self.folder_frame = Frame(self.window)  # 创建文件夹选择框架
        Label(self.folder_frame, text='文件夹路径：'). \
            pack(side=LEFT, padx=5)  # 控件在框架内自左向右排列（排列方式）
        self.folder_var = StringVar()
        Entry(self.folder_frame, textvariable=self.folder_var). \
            pack(side=LEFT, padx=5, fill=X, expand=True)  # 自动填充X轴方向剩余宽度
        self.folder_button = Button(self.folder_frame, text='选择目录', cursor="hand2", command=self.open_folder)
        self.folder_button.pack(side=LEFT, padx=5)
        self.folder_frame.pack(pady=5, fill=X)  # 框架靠左显示，并占满X轴（对齐方式）
        """读取的内容"""
        self.title_frame = Frame(self.window)
        Label(self.title_frame, text='读取的内容：').pack(side=LEFT, padx=5)
        self.title_Text = Text(self.title_frame, height=5)
        self.title_Text.pack(side=LEFT, padx=5, fill=X, expand=True)
        self.title_frame.pack(pady=5, fill=X)
        """提示"""
        self.title_Text_tip = Label(self.window, text='(Tip：使用逗号或顿号分隔)',
                                    font=font.Font(family="楷体", size=10, slant="italic"))
        self.title_Text_tip.pack(anchor=E)  # 靠右对齐
        """排序项和排序方式"""
        self.sort_frame = Frame(self.window)
        Label(self.sort_frame, text='按照').pack(side=LEFT, padx=5)
        self.sort_key_combobox = Combobox(self.sort_frame, values=["文件名称", "修改日期", "文件大小", "文件数字"], width=10)
        self.sort_key_combobox.current(1)
        self.sort_key_combobox.bind("<<ComboboxSelected>>", self.update_file)
        self.sort_key_combobox.pack(side=LEFT, padx=5)
        self.sort_mode_combobox = Combobox(self.sort_frame, values=["升序", "降序"], width=5)
        self.sort_mode_combobox.current(0)
        self.sort_mode_combobox.bind("<<ComboboxSelected>>", self.update_file)
        self.sort_mode_combobox.pack(side=LEFT, padx=5)
        """文件类型"""
        Label(self.sort_frame, text='读取').pack(side=LEFT, padx=5)
        self.file_type_combobox = Combobox(self.sort_frame, values=["Word", "Excel"], width=5)
        self.file_type_combobox.current(0)
        self.file_type_combobox.bind("<<ComboboxSelected>>", self.update_file)
        self.file_type_combobox.pack(side=LEFT, padx=5)
        Label(self.sort_frame, text='文件').pack(side=LEFT, padx=5)
        self.sort_frame.pack(fill=X)
        """确定"""
        self.enter_button = Button(self.window, text='确定', cursor="hand2", width=8, command=self.enter_handle,
                                   font=font.Font(size=16, weight="bold"))
        self.enter_button.pack(pady=20)
        """读取过程"""
        self.progress_label = Label(self.window, text='总进度(0/0)')
        self.progress_label.pack(side=LEFT, padx=5)

    def open_folder(self):
        """
        打开文件夹
        :return:
        """
        folder = filedialog.askdirectory()
        if len(folder) > 0:
            self.folder_var.set(folder)
            self.update_file()

    def update_file(self, event=None):
        """
        更新文件
        :return:
        """
        folder = self.folder_var.get()
        if len(folder) > 0:
            file_type = ".docx" if self.file_type_combobox.get() == "Word" else ".xlsx"
            files = get_sort_file_list(folder,
                                       file_type,
                                       self.sort_key_combobox.get(),
                                       self.sort_mode_combobox.get())
            if len(files) > 0:
                self.progress_label["text"] = "总进度({}/{}): {}".format(0, len(files), os.path.basename(files[0]))
            else:
                self.progress_label["text"] = "总进度(0/0)"

    def enter_handle(self):
        """
        确定处理
        :return:
        """
        """获取用户输入的各个值"""
        folder = self.folder_var.get()
        title = self.title_Text.get("1.0", END)  # 从第一行第一列（即第一个字符）到最后一个字符（end）
        sort_key = self.sort_key_combobox.get()
        sort_mode = self.sort_mode_combobox.get()
        file_type = self.file_type_combobox.get()
        """检验文件夹路径"""
        if len(folder.strip()) == 0:
            messagebox.showwarning("提示", "文件夹路径不能为空")
            return
        """处理并检验读取的内容"""
        title = re.sub(r"\s", "", title)  # 去除空格、换行
        if len(title) == 0:
            messagebox.showwarning("提示", "读取的内容不能为空")
            return
        title = re.split(r"[,、，]", title)  # 分割内容
        """选择文件保存路径"""
        # 返回选择文件的文件名字，但不具备保存文件的能力
        file_name = filedialog.asksaveasfilename(initialfile="报名表汇总.xlsx",  # 默认文件名称
                                                 filetypes=[("XLSX", "*.xlsx")])
        if len(file_name) == 0:
            return
        """判断文件是否打开"""
        if os.path.exists(file_name):
            try:
                file = open(file_name, "a")  # 以追加方式打开
                file.close()
            except PermissionError:
                messagebox.showwarning("提示", "请先关闭已打开的【报名表汇总.xlsx】")
                return
        """根据文件类型调用合并函数"""
        self.enter_button["state"] = DISABLED
        if file_type == "Word":
            result_file = read_word(folder, title, sort_key, sort_mode, self.progress_show)
        else:
            result_file = read_excel(folder, title, sort_key, sort_mode, self.progress_show)
        result_file.save(file_name)
        messagebox.showinfo("提示", "合并完成")
        self.enter_button["state"] = NORMAL

    def progress_show(self, index, length, text):
        """
        显示处理进度
        :param index: 当前读取位置
        :param length: 总长度
        :param text: 当前读取的文件名称
        :return:
        """
        self.progress_label["text"] = "总进度({}/{}): {}".format(index + 1, length, text)

    def reset(self):
        """
        重置
        :return:
        """
        self.folder_var.set("")  # 重置文件夹选择
        self.title_Text.delete("1.0", END)  # 重置读取的内容
        self.sort_key_combobox.current(1)  # 重置排序项
        self.sort_mode_combobox.current(0)  # 重置排序方式
        self.file_type_combobox.current(0)  # 重置文件类型
        self.progress_label["text"] = "总进度(0/0)"


def start():
    """
    启动gui
    :return:
    """
    window = Tk()
    gui = MyGUI(window)
    gui.set_window_style()
    gui.set_window_menu()
    gui.set_window_layout()
    window.mainloop()


if __name__ == "__main__":
    start()
